<!-- daterange picker -->
<link href="/plugins/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />
<div class="row">
    <div class="col-xs-12">
        <div class="box box-default">
            <div class="box-header">
                <div class="alert alert-success alert-dismissable fade in hide" role="alert" id="addSuccess">
                    <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                    <p><i class="icon fa fa-check"></i> <strong>恭喜！</strong>内容添加成功</p>
                </div>
                <p class="myInfoBox bg-warning text-warning"><i class="icon fa fa-warning"></i> 信息填写完整无误才可提交</p>
            </div>
            <div class="box-body">
                <form role="form" class="form-horizontal" name="myForm" ng-submit="processForm(myForm.$valid)" novalidate>
                    <div class="form-group">
                        <label class="control-label col-sm-3">影片标题</label>
                        <div class="col-sm-5">
                            <input type="text" class="form-control input-sm" name="title" ng-minlength="5" ng-maxlength="50" ng-model="formData.title" required/>
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.title.$invalid && !myForm.title.$pristine"><i class="fa fa-times-circle-o"></i> 5-50个非特殊字符</label>

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">别名</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control input-sm" name="alias" ng-minlength="5" ng-maxlength="50" ng-model="formData.alias" required/>
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.alias.$invalid && !myForm.alias.$pristine"><i class="fa fa-times-circle-o"></i> 5-50个非特殊字符</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">导演</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control input-sm" name="director" ng-minlength="5" ng-maxlength="20" ng-model="formData.director" required/>
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.director.$invalid && !myForm.director.$pristine"><i class="fa fa-times-circle-o"></i> 5-20个非特殊字符</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">演员</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control input-sm" name="actor" ng-minlength="5" ng-maxlength="50" ng-model="formData.actor" required/>
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.actor.$invalid && !myForm.actor.$pristine"><i class="fa fa-times-circle-o"></i> 5-50个非特殊字符</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">片长</label>
                        <div class="col-sm-2">
                            <div class="input-group">
                                <input type="text" class="form-control input-sm" name="time" ng-minlength="2" ng-maxlength="5" ng-model="formData.time" required/>
                                <span class="input-group-addon">分钟</span>
                            </div>
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.time.$invalid && !myForm.time.$pristine"><i class="fa fa-times-circle-o"></i> 5-20个非特殊字符</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">上映时间</label>
                        <div class="col-sm-2">
                            <div class="input-group">
                                <div class="input-group-addon">
                                    <i class="fa fa-calendar"></i>
                                </div>
                                <input type="text" class="form-control pull-right" id="reservation"  name="releaseTime" ng-model="formData.releaseTime"/>
                            </div>
                            <!--<label for="inputError" class="control-label text-danger" ng-show="myForm.releaseTime.$invalid && !myForm.releaseTime.$pristine"><i class="fa fa-times-circle-o"></i> 请选择上映时间</label>-->
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">影片类型</label>
                        <div class="col-sm-4">
                            <div class="input-group margin">
                                <input type="text" class="form-control" name="tags" id="typeSel" ng-minlength="2" ng-maxlength="27" ng-model="formData.filmType" onclick="showFileTypesMenu()" required/>

                                <div class="input-group-btn">
                                    <button type="button" class="btn btn-default dropdown-toggle"  id="menuBtn" onclick="showFileTypesMenu(); return false;">选择 <span class="fa fa-caret-down"></span></button>
                                    <div id="menuContent" class="menuContent" style="display:none; position: absolute;border: 1px solid #ccc;border-radius: 5px;left: -14px;top: 43px;z-index: 999">
                                        <ul class="ztree" id="typesTree" style="margin-top:0; width:180px; max-height: 200px;"></ul>
                                    </div>
                                </div><!-- /btn-group -->
                            </div><!-- /input-group -->
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.filmType.$invalid && !myForm.filmType.$pristine"><i class="fa fa-times-circle-o"></i>标签用逗号隔开，单个标签不可超过6个字，不得超过4个标签</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">剧照</label>
                        <div class="col-sm-3">
                            <input type="file" name="uploadify" id="uploadify" />
                            <img src="" alt="" width="120" height="120" class="img-thumbnail" id="myImg">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">影片大类</label>
                        <div class="col-sm-2">
                            <div class="dropdown">
                                <button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <i id="categoryName">请选择影片类别</i>
                                    <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel" id="treeDemo" class="ztree">
                                    <li role="presentation"><a href="#">test</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">关键字</label>
                        <div class="col-sm-2">
                            <input type="text" class="form-control input-sm" name="keywords" ng-minlength="2" ng-maxlength="20" ng-model="formData.keywords" required/>
                            <label for="inputError" class="control-label text-danger" ng-show="myForm.keywords.$invalid && !myForm.keywords.$pristine"><i class="fa fa-times-circle-o"></i>20个字以内，多个关键字之间用逗号隔开</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3">影片详情</label>
                        <div class="col-sm-6">
                            <textarea class="" name="comments" ng-model="formData.comments" id="container" ng-minlength="50" placeholder="请输入文章详情" ueditor>{{formData.comments}}</textarea>
                            <!--<label for="inputError" class="control-label text-danger" ng-show="myForm.comments.$invalid && !myForm.comments.$pristine"><i class="fa fa-times-circle-o"></i>内容不得少于50个字</label>-->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid">提交</button>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>
<script src="/plugins/daterangepicker/daterangepicker.js" type="text/javascript"></script>

<script>

    $(function(){
        //Date range picker
        $('#reservation').daterangepicker();

    })

    angular.module("adminApp",[])
            .controller("adminCtrl",function($scope,$http){
                $scope.formData = {};
//                初始化文章分类
                iniTreeData($scope,$http);
//                初始化文章属性
                initContentTypes($scope,$http);
//                初始化上传按钮
                initUploadBtn($scope);
//                通过访问地址获取文章id
                $scope.targetID = window.location.href.split("/")[8];
                if($scope.targetID){
                    $http.get("/admin/manage/content/item?uid="+$scope.targetID).success(function(result){

                        iniTreeData($scope,$http);
                        initContentTypes($scope,$http);
                        $scope.formData = result;
                        $("#myImg").attr("src",$scope.formData.sImg)
                    })
                }
                // 添加或修改文章
                $scope.processForm = function(isValid){
                    $scope.formData.type = "film";
                    $scope.formData.releaseTime = $("#reservation").val();
                    $scope.formData.author = "dora";
                    var url = "/admin/manage/content/addcontent";
                    if($scope.targetID){
                        url = "/admin/manage/content/modify?uid="+$scope.targetID;
                    }
                    if(isValid){
                        $http({
                            method  : 'POST',
                            url     : url,
                            data    : $.param($scope.formData),  // pass in data as strings
                            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
                        })
                                .success(function(data) {
                                    if(data === "success"){
                                       window.location = "/admin/manage/contentList";
                                    }else{
                                        alert("未知异常，请稍后重试");
                                    }
                                });
                    }
                    else{
                        alert("校验失败，请检查");
                    }
                }
            })
            .directive('ueditor', function ($timeout) { //angular绑定ueditor
                return {
                    restrict: 'A',
                    require: 'ngModel',
                    link: function (scope, element, attrs, ctrl) {
                        var id = 'ueditor_' + Date.now();
                        element[0].id = id;
                        var ue = UE.getEditor(id, {
                            initialFrameWidth: '100%',
                            initialFrameHeight: '500',
                            autoHeightEnabled: true
                        });
                        ue.ready(function () {
                            ue.addListener('contentChange', function () {
                                ctrl.$setViewValue(ue.getContent());
                                if (!scope.$$phase) {
                                    scope.$apply();
                                }
                            });
                        });
                    }
                };
            });

           function iniTreeData($scope,$http){
               $http.get("/admin/manage/contentCategorys/list").success(function(result){
                   var categoryName = $("#categoryName");
                   if($scope.formData){
                       categoryName.html(getCateNameById(result,$scope.formData.category));
                   }

                   var arrTree = changeToTreeJson(result);
                   var setting = {
                       view: {
                           dblClickExpand: false,
                           selectedMulti: false
                       },
                       data: {
                           simpleData: {
                               enable: true
                           }
                       },
                       callback: {
                           beforeClick: beforeClick,
                           onClick: onClick
                       }
                   };

                   function beforeClick(treeId, treeNode) {
                       var check = (treeNode && !treeNode.isParent);
                       if (!check) alert("不能选择顶级分类");
                       return check;
                   }

                   function onClick(e, treeId, treeNode) {
                       var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                               nodes = zTree.getSelectedNodes(),
                               v = "",
                               vid = "",
                               sortPath = "",
                               contentTemp = "";


                       nodes.sort(function compare(a,b){return a.id-b.id;});
                       for (var i=0, l=nodes.length; i<l; i++) {
                           v += nodes[i].name ;
                           vid += nodes[i].id ;
                           sortPath += nodes[i].sortPath ;
                           contentTemp += nodes[i].contentTemp ;
                       }

                       categoryName.html(v);
                       $scope.formData.category = vid;
                       $scope.formData.sortPath = sortPath;
//                       设置文章模板
                       $scope.formData.contentTemp = contentTemp;
                   }

                   $.fn.zTree.init($("#treeDemo"), setting, arrTree);
               })
           }


            function initContentTypes($scope,$http){
                $http.get("/admin/manage/contentAttributes/allByParam?typeId=0").success(function(result){
                    var oldfilmTypes = $scope.formData.filmType;

                    if(!oldfilmTypes){
                        oldfilmTypes = "0";
                    }
                    var typesTree = changeToTreeJson(result,"filmTypes",oldfilmTypes);
                    var setting = {
                        check: {
                            enable: true,
                            chkboxType: {"Y":"", "N":""}
                        },
                        view: {
                            dblClickExpand: false
                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        },
                        callback: {
                            beforeClick: beforeTagsClick,
                            onCheck: onTagsCheck
                        }
                    };

                    var zNodes = typesTree;
                    $.fn.zTree.init($("#typesTree"), setting, zNodes);

                    function beforeTagsClick(treeId, treeNode) {
                        var zTree = $.fn.zTree.getZTreeObj("typesTree");
                        zTree.checkNode(treeNode, !treeNode.checked, null, true);
                        return false;
                    }

                    function onTagsCheck(e, treeId, treeNode) {
                        var zTree = $.fn.zTree.getZTreeObj("typesTree"),
                                nodes = zTree.getCheckedNodes(true),
                                v = "";
                        for (var i=0, l=nodes.length; i<l; i++) {
                            if(i > 3){
                                return;
                            }
                            v += nodes[i].name + ",";
                        }
                        if (v.length > 0 ) {
                            v = v.substring(0, v.length-1);
                        }
                        var tagObj = $("#typeSel");
                        tagObj.val("");
                        tagObj.val(v);
                        tagObj.attr("value", v);
                        $scope.formData.filmType = v;

                    }
                })
            }

            function showFileTypesMenu() {
                var cityObj = $("#typeSel");
                var cityOffset = $("#typeSel").offset();
                $("#menuContent").slideDown("fast");

                $("body").bind("mousedown", onBodyDown);
            }
            function hideTagsMenu() {
                $("#menuContent").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);
            }
            function onBodyDown(event) {
                if (!(event.target.id == "menuBtn" || event.target.id == "typeSel" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
                    hideTagsMenu();
                }
            }



            function initUploadBtn($scope){
                $("#uploadify").uploadify({
                    //指定swf文件
                    'swf': '/plugins/uploadify/uploadify.swf',
                    //后台处理的页面
                    'uploader': '/system/upload?type=images&key=ctTopImg',
                    //按钮显示的文字
                    'buttonText': '上传图片',
                    //显示的高度和宽度，默认 height 30；width 120
                    //'height': 15,
                    //'width': 80,
                    //上传文件的类型  默认为所有文件    'All Files'  ;  '*.*'
                    //在浏览窗口底部的文件类型下拉菜单中显示的文本
                    'fileTypeDesc': 'Image Files',
                    //允许上传的文件后缀
                    'fileTypeExts': '*.gif; *.jpg; *.png',
                    //发送给后台的其他参数通过formData指定
//                    'formData': { 'type': 'images', 'key': 'ctTopImg' },
                    //上传文件页面中，你想要用来作为文件队列的元素的id, 默认为false  自动生成,  不带#
                    //'queueID': 'fileQueue',
                    //选择文件后自动上传
                    'auto': true,
                    //设置为true将允许多文件上传
                    'multi': true,
                    //上传成功
                    'onUploadSuccess' : function(file, data, response) {
//                alert("success"+data)
                        $("#myImg").attr("src",data);
                        $scope.formData.sImg = data;
                    },
                    'onComplete': function(event, queueID, fileObj, response, data) {//当单个文件上传完成后触发
                        //event:事件对象(the event object)
                        //ID:该文件在文件队列中的唯一表示
                        //fileObj:选中文件的对象，他包含的属性列表
                        //response:服务器端返回的Response文本，我这里返回的是处理过的文件名称
                        //data：文件队列详细信息和文件上传的一般数据

                        alert("文件:" + fileObj.name + " 上传成功！");
                    },
                    //上传错误
                    'onUploadError' : function(file, errorCode, errorMsg, errorString) {
                        alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
                    },
                    'onError': function(event, queueID, fileObj) {//当单个文件上传出错时触发
                        alert("文件:" + fileObj.name + " 上传失败！");
                    }
                });
            }
</script>